package com.hnkywl.sts.service.cwgl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.cwgl.FpdrDao;
import com.hnkywl.sts.dao.cwgl.KmdmDao;
import com.hnkywl.sts.dao.cwgl.YwcbDao;
import com.hnkywl.sts.dao.jsgl.FpDao;
import com.hnkywl.sts.dao.jsgl.JsdhbDao;
import com.hnkywl.sts.entity.cggl.Jsd;
import com.hnkywl.sts.entity.cggl.Jsdhb;
import com.hnkywl.sts.entity.cwgl.Kmdm;
import com.hnkywl.sts.entity.cwgl.VoucherItemData;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sfgl.Sfk;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.xsgl.Xsd;
import com.hnkywl.sts.entity.zjgl.Pjdr;
import com.hnkywl.sts.service.jsgl.XsjsdService;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-4-30
 * Time: 上午9:58
 * To change this template use File | Settings | File Templates.
 */
@Service
public class YwcbService {
    private YwcbDao ywcbDao;
    private KmdmDao kmdmDao;

    public String findAllYwcb(String xsdh, Date fhsjStart, Date fhsjEnd, Long xshtId, Long khId, Long gcId, Long sbgsId, Long sbbmId, Long sbrId, String zt, String cxzt, String sftzd, String xslx,Boolean dlkhxsd, int pageNo, int pageSize) throws ParseException {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Page xsdPage = this.ywcbDao.findYwcbList(xsdh, fhsjStart, fhsjEnd, xshtId, khId, gcId, sbgsId, sbbmId, sbrId, zt, cxzt, sftzd, xslx, dlkhxsd, pageNo, pageSize);
        List<Map<String,Object>> xsdList = xsdPage.getResult();
        if(xsdList.size()>0){
            xsdList = getCzztByPj(xsdList);
        }
        String xsdJson = gson.toJson(xsdPage.getResult());
//        List<Map> sumList = this.ywcbDao.findSumYwcb(xsdh, fhsjStart, fhsjEnd, xshtId, khId, gcId, sbgsId, sbbmId, sbrId, zt, cxzt, sftzd, xslx,dlkhxsd);
//        Double xsjs = 0d;
//        Double xssl = 0d;
//        Double xsje = 0d;
//        Double gylfyje = 0d;
//        if (sumList.size() != 0) {
//            for (Map map : sumList) {
//                xsjs += Double.valueOf((map.get("xsjs") == null ? 0d : map.get("xsjs")).toString());
//                xssl += Double.valueOf((map.get("xssl") == null ? 0d : map.get("xssl")).toString());
//                xsje += Double.valueOf((map.get("xsje") == null ? 0d : map.get("xsje")).toString());
//
//                gylfyje += Double.valueOf((map.get("gylfyje") == null ? 0d : map.get("gylfyje")).toString());
//            }
//            return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + ",\"footer\":[{\"xsdh\":\"合计:\",\"xsjs\":" + xsjs + ",\"xssl\":" + xssl + ",\"xsje\":" + xsje + ", \"gylfyje\":" + gylfyje + " }]}";
//        } else {
            return "{\"total\":" + xsdPage.getTotalCount() + ",\"rows\":" + xsdJson + "}";
//        }
    }

    public List<Map<String,Object>> getCzztByPj(List<Map<String,Object>> xsdList){
        for(Map<String,Object> x:xsdList){
            String czzt = "";
            if(Integer.parseInt(x.get("insertFlag").toString())==1 && Integer.parseInt(x.get("deleteFlag").toString())==1){
                czzt = "wdr";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==1 && Integer.parseInt(x.get("deleteFlag").toString())==3){
                czzt = "sccg";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==3 && Integer.parseInt(x.get("deleteFlag").toString())==1){
                czzt = "drcg";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==2 && Integer.parseInt(x.get("deleteFlag").toString())==1 ||
                    Integer.parseInt(x.get("insertFlag").toString())==2 && Integer.parseInt(x.get("deleteFlag").toString())==3 ){
                czzt = "drsb";
            }else if(Integer.parseInt(x.get("insertFlag").toString())==3 && Integer.parseInt(x.get("deleteFlag").toString())==2){
                czzt = "scsb";
            }else{
                czzt = "null";
            }
            x.put("CZZT", czzt);
        }
        return xsdList;
    }


    @Transactional
    public Map getVoucherMaster(Long id, Integer attachment, String uuid, String year, String mouth, Yg yg) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Map<String, Object> voucherMaster = new HashMap<String, Object>();
        Xsd result = ywcbDao.get(id);
        voucherMaster.put("id", uuid);
        voucherMaster.put("vchrtypecode", "记");//凭证类别
        voucherMaster.put("acctyear", year != null ? year : "");//会计年度
        voucherMaster.put("acctperiod", mouth != null ? mouth : "");//会计期间
        voucherMaster.put("createdate", systemDate);//凭证日期
        voucherMaster.put("unitcode", result.getSbgs() != null && result.getSbgs().getJiuqiUnitCode() != null ? result.getSbgs().getJiuqiUnitCode() : "");//组织机构代码
        voucherMaster.put("acctbookcode", "01");//账薄标识
        voucherMaster.put("createuser", yg.getXm());//制单人
        voucherMaster.put("attachment", attachment);//附件张数
        voucherMaster.put("memo", "");//备注
        voucherMaster.put("companyId", result.getSbgs().getId());//公司ID
        return voucherMaster;
    }


    //财务收付分录
    @Transactional
    public String findQtpzfl(Long id) {
        Xsd ywcb = this.ywcbDao.get(id);
        List<Map> list = this.ywcbDao.getVoucher(ywcb);
        List<Map> txcdJson = new ArrayList<Map>();
        for (int i =0;i<list.size() ;  i++){
            Map<String, Object> voucherItem = (Map<String, Object>)list.get(i);
            voucherItem.put("zy",voucherItem.get("digest"));
            voucherItem.put("km",voucherItem.get("subjectname"));
            voucherItem.put("jf",voucherItem.get("debit"));
            voucherItem.put("df",voucherItem.get("credit"));
            txcdJson.add(voucherItem);
        }
        return new Gson().toJson(txcdJson);
    }

    @Transactional
    public void ywcbChangeDrrq(Long cwsfId,Date date){
        Xsd x = this.ywcbDao.get(cwsfId);
        x.setDrrq(date);
        ywcbDao.save(x);
    }

    @Transactional
    public Map getU8VoucherItems(Long id, String uuid,List<VoucherItemData> voucherItemDataList,Date documentDate) {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String systemDate =simple.format(new Date());
        Xsd xsd = this.ywcbDao.get(id);
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map> list = this.ywcbDao.getVoucher(xsd);
        DecimalFormat df = new DecimalFormat("#.##");
        //凭证分录信息
        List<Map> items = new ArrayList<Map>();
        int order = 1;
        for(Map m : list){
            Map<String, Object> voucherItem = new HashMap<String, Object>();
            voucherItem.put("entry_id", order);//分录编号
            voucherItem.put("account_code", m.get("account_code") != null ? m.get("account_code") : "");//科目代码
            voucherItem.put("natural_debit_currency", m.get("debit") != null ? df.format(m.get("debit")) : "0.00");//借方金额
            voucherItem.put("natural_credit_currency", m.get("credit")!= null ? df.format(m.get("credit")) : "0.00");//贷方金额
            voucherItem.put("unit_price", "0");//单价,在科目有数量核算时，填写此项
            voucherItem.put("debit_quantity", "0");//借方数量,在科目有数量核算时，填写此项
            voucherItem.put("credit_quantity", "0");//贷方数量,在科目有数量核算时，填写此项
            voucherItem.put("currency", "CNY");//货币代码
            voucherItem.put("exchange_rate2", "1.000000");//汇率
            voucherItem.put("settlement", "");//结算方式,在科目是银行或往来时，可以填写此项
            voucherItem.put("document_id", "");//票据号，在科目是银行或往来时，可以填写此项
            voucherItem.put("document_date",systemDate);//票据日期，在科目是银行或往来时，可以填写此项
            voucherItem.put("abstract", m.get("digest") != null ? m.get("digest") : "");//摘要
            Map<String, String> fzhsMap = new HashMap<String, String>();
            Map<String, Map> xjllxmMap = new HashMap<String, Map>();
            fzhsMap =  this.findFzhsByMap(xsd,m,fzhsMap,xjllxmMap);
            voucherItem.put("auxiliary_accounting", fzhsMap);
            voucherItem.put("cash_flow", xjllxmMap);
            items.add(voucherItem);
            order++;
        }
        result.put("items", items);
        return result;
    }

    private Map<String,String > findFzhsByMap(Xsd xsd, Map<Object,String> map,Map<String, String> fzhsMap, Map<String, Map> xjllxmMap){
            if(map.get("dept_id") !=null && !map.get("dept_id").toString().equals("")){
                fzhsMap.put("dept_id",map.get("dept_id"));
            }
            if(map.get("personnel_id") !=null && !map.get("personnel_id").toString().equals("")){
                fzhsMap.put("personnel_id",map.get("personnel_id"));
            }
            if(map.get("cust_id") !=null && !map.get("cust_id").toString().equals("")){
                fzhsMap.put("cust_id",map.get("cust_id"));
            }
            if(map.get("supplier_id") !=null && !map.get("supplier_id").toString().equals("")){
                fzhsMap.put("supplier_id",map.get("supplier_id"));
                fzhsMap.put("operator","-");
            }
        return fzhsMap;
    }

    @Transactional
    public Map getRevokeInfo(Long id) {
        Map<String, Object> revokeInfo = new HashMap<String, Object>();
        Xsd result = ywcbDao.get(id);
        if (result == null) {
            throw new RuntimeException("未获取凭证信息!");
        }
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("MM");
        revokeInfo.put("id", result.getUuid());//凭证ID
        revokeInfo.put("vchrid", result.getVoucherId());//凭证ID
        revokeInfo.put("unitcode",result.getCreateOrgan() != null && result.getCreateOrgan().getJiuqiUnitCode() != null ? result.getCreateOrgan().getJiuqiUnitCode() : "");//单位代码
        revokeInfo.put("vchrtypecode", "记");//会计年度
        revokeInfo.put("acctyear", result.getAcctyear());//会计年度
        revokeInfo.put("acctperiod",simpleDateFormat3.format(result.getDrrq()));//会计年度
        revokeInfo.put("vchrnum", result.getVoucherNum());//凭证号

        return revokeInfo;
    }


   @Autowired
    public void setYwcbDao(YwcbDao ywcbDao) {
        this.ywcbDao = ywcbDao;
    }
}
